package com.example.backend.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.backend.common.Result;
import com.example.backend.entity.Entity;
import com.example.backend.entity.User;
import com.example.backend.mapper.EntityMapper;
import com.example.backend.mapper.ProgramMapper;
import com.example.backend.mapper.UserMapper;
import com.example.backend.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserMapper userMapper;

    @Resource
    EntityMapper entityMapper;

    @Resource
    ProgramMapper programMapper;

    @PostMapping("/register")
    public Result<?> save(@RequestBody User user){
        User tem = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId,user.getId()));
        if (tem==null){
            userMapper.insert(user);
            return Result.success();
        }
        return Result.error("-1","用户名已存在");
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User userParam){
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId,userParam.getId()).eq(User::getPassword,userParam.getPassword()));
        if (res == null){
            return Result.error("-1","用户名或密码错误");
        }
        String token = TokenUtils.genToken(res);
        res.setToken(token);
        res.setPassword("");    //不传密码
        return Result.success(res);
    }

}
